<?php

class User_Self extends User_Abstract
{
    public function __construct($user_id)
    {
        parent::__construct($user_id);
        self::$_dbh = Framework_Registry::get('dbh');
    }
    
    public function __destruct()
    {
        self::$_dbh->query("UPDATE user SET user_last_visit=NOW() WHERE user_id=?", $this->_userId);
    }
    
    /**
     * Устанавливает аватарку
     * 
     * @param string $file
     * @return int
     */
    public function setAvatar($file)
    {
        return empty($file) ? null : self::$_dbh->query("UPDATE ?_user SET user_avatar=? WHERE user_id=?", $file, $this->_userId);
    }
    
    /**
     * Берет аватарку
     * 
     * @return int
     */
    public function getAvatar()
    {
        return self::$_dbh->selectCell("SELECT user_avatar FROM ?_user WHERE user_id=?", $this->_userId);
    }
    
    /**
     * Устанавливает путь до папки юзера
     * 
     * @param string $path
     * @return int
     */
    public function setPath($path)
    {
        return empty($path) ? null : self::$_dbh->query("UPDATE ?_user SET user_path=? WHERE user_id=?", $path, $this->_userId);
    }
    
    /**
     * Вовращает объект User_Self при корректных логине и пароле и null
     * в обратном случае.
     * 
     * @param string $login
     * @param string $pass
     * @return int 
     */
    public static function getCorrectUser($login, $pass)
    {
        if (empty($login) || empty($pass)) return null;
        $user_id = Framework_Registry::get('dbh')
            ->selectCell("SELECT user_id FROM `user`
                          WHERE LOWER(user_login)=LOWER(?) AND user_password=?",
                          $login, md5($pass));
        
        return empty($user_id) ? null : new self($user_id);
    }
    
    /**
     * Возвращает объект User_Self если такой логин существует, и null в
     * противном случае
     * 
     * @param string $username
     * @return int
     */
    public static function findUserIdByLogin($username)
    {
        $user_id = parent::findUserIdByLogin($username);
        
        return empty($user_id) ? null : new self($user_id);
    }
    
    public static function findUserIdByPhone($phone)
    {
        $user_id = parent::findUserIdByPhone($phone);
        
        return empty($user_id) ? null : new self($user_id);
    }
    
    /**
     * Возвращает объект User_Self если такой user_id существует, и null в
     * противном случае
     * 
     * @param string $username
     * @return int
     */
    public static function findLoginByUserId($user_id)
    {
        $user_id = parent::findLoginByUserId($user_id);

        return empty($user_id) ? null : new self($user_id);
    }
    
    /**
     * Создает пользователя при регистрации
     * 
     * @param array $form
     * @return User_Self
     */
    public static function createUser(array $form)
    {
        if(!sizeof($form)) return null;
        $user_id = Framework_Registry::get('dbh')->query('INSERT INTO user SET
                                                               user_login=?,
                                                               user_number=?,
                                                               user_password=?,
                                                               user_mail=?,
                                                               user_sex=?,
                                                               user_born=?,
                                                               user_country=?,
                                                               user_city=?,
                                                               user_description=?,
                                                               user_created=NOW()',
                                                               
                                                               $form['username'],
                                                               $form['number'],
                                                               md5($form['password']),
                                                               $form['mail'],
                                                               $form['sex'],
                                                               $form['born'],
                                                               $form['country'],
                                                               $form['city'],
                                                               $form['description']);

        return empty($user_id) ? null : new self($user_id);
    }
    
    /**
     * проверяем возможность восстановить пароль по логину, мылу или номеру
     * @param str $login
     * @param str $msisdn
     * @param str $mail
     * @author kiote
     * @return User_Self|false
     */
    public static function tryToRecover($login = '', $msisdn = '', $mail = '')
    {
        $rows = Framework_Registry::get('dbh')->
            selectRow("SELECT user_id FROM `user`
                       WHERE user_login = ? 
                       OR user_mail = ? 
                       OR user_number = ?", $login, $mail, $msisdn);
        return ($rows) ? new self($rows['user_id']) : false;
    }
    
    /**
     * готовимся восстанавливать пароль - заполняем поле user_pass_recover
     * @param int $user_id
     * @author kiote
     */
    public function recoverConfirm()
    {
       $user_id = $this->getUserId();
       // получаем мыло и номер
       $row = self::$_dbh->
            selectRow("SELECT user_number, user_mail
                        FROM `user`
                        WHERE user_id = ?",$user_id);
       $salt = time();
       $pass_recover = md5(rand(0,10000)) . $salt;
       //выставляем признак сброса пароля
       Framework_Registry::get('dbh')->
        query("UPDATE user 
                SET user_pass_recover = ? 
                WHERE user_id = ?", $pass_recover, $user_id);
       if ($row) {
            $this->_sendRecoverUrl($row['user_number'],$row['user_mail'], $pass_recover);
       }
    }
    
    private function _sendRecoverUrl($msisdn, $mail, $pass_recover)
    {
    	$meta = Meta::getInstance();
    	$meta->load('recover_pass_text');
    	$message = $meta->get('recover_pass_text');
    	$message .= $pass_recover;
    	mail($mail, 'Vote & Flirt Chat: Password recovery', 
    	   $message);
    }
    
    /**
     * задаем новый пароль
     * @author kiote
     * @param str $user_pass_recover 
     * @return str new password
     */
    public function realRecover($user_pass_recover)
    {
    	$rows = Framework_Registry::get('dbh')->
            selectRow("SELECT user_id FROM `user`
                       WHERE user_pass_recover = ?", $user_pass_recover);
        return ($rows) ? new self($rows['user_id']) : false;
    }
    
    public function passwd()
    {
    	$pass = $this->_generatePass();
    	$rows = Framework_Registry::get('dbh')->
            query("UPDATE user SET 
                    user_pass_recover = '', 
                    user_password = md5(?)
                   WHERE user_id = ?", $pass, $this->getUserId());
        return $pass;
    }
    
    private function _getMail()
    {
    	$rows = Framework_Registry::get('dbh')->
            selectRow("SELECT user_mail FROM `user`
                       WHERE user_id = ?", $this->getUserId());
        return ($rows) ? $rows['user_mail'] : false;
    }
    
    public function sendNewPass($passwd)
    {
    	$mail = $this->_getMail();
        $message = 'Your new password: '.$passwd;
        mail($mail, 'Vote & Flirt Chat: Password recovery', 
           $message);
    }
    
    private function _generatePass()
    {
    	$pass_from[0] = '0 1 2 3 4 5 6 7 8 9';
        $pass_from[1] = 'q w e r t y u i o p a s d f g h j k l z x c v b n 
                            m Q W E R T Y U I O P A S D F G H J K L Z X C V
                            B N M';
        $pass = '';
        for ($i=1; $i<8; $i++){
        	$j = intval(time() % 2 == 1); // letter or digit
        	$pass .= array_rand(explode(' ',$pass_from[$j]));
        }
        return $pass;
    }
    
    /**
     * Добавляет нового друга
     * 
     * @param int $friend_id
     * @return int 
     */
    public function addFriend($user_id)
    {
        return empty($user_id) ? null :
            self::$_dbh->query('INSERT INTO ?_friend
                                SET friend_user_id_from=?, friend_user_id_to=?',
                                $this->_userId, $user_id);
    }
    
    /**
     * Удаляет друга
     * 
     * @param int $friend_id
     * @return int 
     */
    public function delFriend($user_id)
    {
        return empty($user_id) ? null :
            self::$_dbh->query("DELETE FROM ?_friend
                                WHERE friend_user_id_from=?
                                    AND friend_user_id_to",
                                $this->_userId, $user_id);
    }
    
    /**
     * Добавить в Black list
     * 
     * @param int $user_id
     * @return int 
     */
    public function addToBlackList($user_id)
    {
        return empty($user_id) ? null :
            @self::$_dbh->query("INSERT INTO ?_block
                                SET block_user_id_from=?, block_user_id_to=?",
                                $this->_userId, $user_id);
    }
    
    /**
     * Удалить из Black list
     * 
     * @param int $user_id
     * @return int 
     */
    public function delFromBlackList($user_id)
    {
        return empty($user_id) ? null :
            self::$_dbh->query("DELETE FROM ?_block
                                WHERE block_user_id_from=?
                                    AND block_user_id_to",
                                $this->_userId, $user_id);
    }
    
    /**
     * Проверяет друг он мне иль не друг
     * 
     * @param string $user_id
     * @return int
     */
    public function isFriend($user_id)
    {
        return empty($user_id) ? null :
            self::$_dbh->selectCell("SELECT COUNT(*)
                                     FROM friend
                                     WHERE friend_user_id_from=?
                                        AND friend_user_id_to=?",
                                     $this->_userId, $user_id);
    }
    
    /**
     * Проверяет заблокирован ли пользователь
     * 
     * @param string $user_id
     * @return int
     */
    public function isBlock($user_id)
    {
        return empty($user_id) ? null :
            self::$_dbh->selectCell("SELECT COUNT(*)
                                     FROM block
                                     WHERE block_user_id_from=?
                                        AND block_user_id_to=?",
                                     $this->_userId, $user_id);
    }
    
    public function activate()
    {
        return self::$_dbh->query('UPDATE user
                                   SET user_active=1
                                   WHERE user_id=?', $this->_userId);
    }
    
    public function getVisitors($sum = 10, $page = 0, &$paging = 0)
    {
        $result = self::$_dbh->selectPage($total_rows,
                                       'SELECT * FROM visitor
                                        LEFT JOIN user ON user_id = visitor_user_id_from
                                        WHERE visitor_user_id_to=?
                                        ORDER BY visitor_updated DESC LIMIT ?d, ?d',
                                        $this->_userId,
                                        $page*$sum, $sum);
        $paging = paging($page, $sum, $total_rows);
        
        return $result;
    }
    
    public function getTotalVisitors()
    {
        return self::$_dbh->selectCell('SELECT COUNT(*) FROM visitor
                                        WHERE visitor_user_id_to=?',
                                        $this->_userId);
    }
    
    public function isVote($user_id)
    {
        return empty($user_id) ? null : self::$_dbh
            ->selectCell('SELECT rating_score
                          FROM ?_rating
                          WHERE rating_user_id_from=? AND rating_user_id_to=?',
                          $this->_userId, $user_id);
    }
    
    public function vote($user_id, $rating)
    {
        return empty($rating) || empty($user_id) ? null : @self::$_dbh
            ->query('INSERT INTO ?_rating
                     SET rating_user_id_from=?, rating_user_id_to=?, rating_score=?',
                     $this->_userId, $user_id, $rating);
    }
	
	//kiote
	public function nullRating($user_id)
	{
		return  empty($user_id) ? null : @self::$_dbh
            ->query("DELETE FROM ?_rating
						WHERE rating_user_id_to = ?", $user_id);
	}

    public function setData($form)
    {
        return self::$_dbh->query('UPDATE user
                                   SET user_mail=?,
                                       user_sex=?,
                                       user_born=?,
                                       user_country=?,
                                       user_city=?,
                                       user_description=?
                                   WHERE user_id=?',
                                   $form['user_mail'],
                                   $form['user_sex'],
                                   $form['user_born'],
                                   $form['user_country'],
                                   $form['user_city'],
                                   $form['user_description'],
                                   $this->_userId);
    }
    
    public function setNewPassword($password, $old_password = null)
    {
    	 return self::$_dbh->query('UPDATE user
    	                           SET user_password=?
    	                           WHERE user_id=?
    	                            { AND user_password=? }',
    	                           md5($password),
    	                           $this->_userId,
    	                           empty($old_password) ? DBSIMPLE_SKIP : md5($old_password));
    }
    
    public function ReportAbuse ($user_id, $message)
    {
    	return empty($user_id) || empty($message) ? null : self::$_dbh
    	   ->query('INSERT INTO abuse
    	            SET abuse_user_id_from=?, abuse_user_id_to=?, abuse_reason=?',
    	            $this->_userId, $user_id, $message);
    }

    public function getRoomsForInvite($user_id)
    {
        return empty($user_id) ? null : Framework_Registry::get('dbh')
            ->select("SELECT * FROM room
                      LEFT JOIN invite ON invite_room_id = room_id
                      WHERE room_status = 'close' AND invite_user_id_to=? AND invite_room_id NOT IN (
                          SELECT invite_room_id
                          FROM invite
                          WHERE invite_user_id_to=?)",
                      $this->_userId, $user_id);
    }

    public function getNewMessagesCount()
    {
        return self::$_dbh->selectCell("SELECT COUNT(*) FROM ?_message
                                        WHERE message_user_id_to=? AND message_read IS NULL",
                                        $this->_userId);
    }
    
     /**
     * Список сообщений
     * 
     * @return array 
     */
    public function getMessages($courese, $sum = 10, $page = 0, &$paging = array())
    {
        switch ($courese) {
            case 'from':
                $to = 'message_user_id_from';
                $from = 'message_user_id_to';
                break;
            default:
                $to = 'message_user_id_to';
                $from = 'message_user_id_from';
                break;
        }
        $rows =  self::$_dbh->selectPage($total_rows,
                                   "SELECT SQL_CALC_FOUND_ROWS * FROM ?_message
                                    LEFT JOIN ?_user ON user_id = $from
                                    WHERE $to=? ORDER BY message_created DESC LIMIT ?d, ?d", $this->_userId, $page*$sum, $sum);
        $paging = paging($page, $sum, $total_rows);
        
        return $rows;
    }
    
    /**
     * Посылает сообщение
     * 
     * @param string $user_id
     * @param array $form
     * @return int
     */
    public function sendMessage($user_id, array $form, $strip = true)
    {
        if (empty($user_id) || !sizeof($form)) {
            return null;
        }

        return self::$_dbh->query('INSERT INTO ?_message
                                   SET message_user_id_from=?,
                                       message_user_id_to=?,
                                       message_title=?,
                                       message_content=?',
                                   $this->_userId,
                                   $user_id,
                                   $strip ? strip_tags($form['title']) : $form['title'],
                                   $strip ? strip_tags($form['content']) : $form['content']);
    }
    
    /**
     * Сообщение
     * 
     * @return int 
     */
    public function getHistoryTalk($message_id, $user_id, $limit = 10)
    {
        return self::$_dbh->select('SELECT * FROM ?_message
                                    LEFT JOIN ?_user ON message_user_id_from = user_id
                                    WHERE message_id<? AND ((message_user_id_from=? AND message_user_id_to=?) OR (message_user_id_from=? AND message_user_id_to=?))
                                    ORDER BY message_id DESC LIMIT ?d',
                                       $message_id, $user_id, $this->_userId, $this->_userId, $user_id, $limit);
    }
    
    /**
     * Сообщение
     * 
     * @return int 
     */
    public function getMessage($message_id)
    {
        return self::$_dbh->selectRow('SELECT * FROM ?_message
                                       LEFT JOIN ?_user ON user_id = message_user_id_from
                                       WHERE message_id=?', $message_id);
    }
    
    /**
     * Удаляет сообщение
     * 
     * @return int 
     */
    public function delMessage($message_id)
    {
        return self::$_dbh->query('DELETE FROM ?_message
                                   WHERE message_id=? AND message_user_id_to=?',
                                   $message_id, $this->_userId);
    }
    
    /**
     * Ставим флаг прочтения сообщения
     * 
     * @return array 
     */
    public function readMessage($message_id)
    {
        return self::$_dbh->query("UPDATE ?_message SET message_read='1'
                                   WHERE message_id=? AND message_user_id_from!=?",
                                   $message_id, $this->_userId);
    }

    public function getLastVotingUser()
    {
        return self::$_dbh->selectRow('SELECT * FROM rating
                                       LEFT JOIN user ON rating_user_id_from = user_id
                                       WHERE rating_user_id_from=?
                                       ORDER BY rating_id DESC
                                       LIMIT 1',
                                       $this->_userId);
    }
}